package com.sptus.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwk.Jwk;
import io.jsonwebtoken.*;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.client.RestTemplate;

import java.security.PublicKey;

public class JWTutil {
    /**
     * 对前端传来的JWT字符串identityToken的第二部分进行解码
     * 主要获取其中的aud和sub，aud大概对应ios前端的包名，sub大概对应当前用户的授权的openID
     *
     * @param identityToken 身份token
     * @return {"aud":"com.xkj.****","sub":"000***.8da764d3f9e34d2183e8da08a1057***.0***","c_hash":"UsKAuEoI-****","email_verified":"true","auth_time":1574673481,"iss":"https://appleid.apple.com","exp":1574674081,"iat":1574673481,"email":"****@qq.com"}
     */
    public static JSONObject parserIdentityToken(String identityToken, String type) {
        String[] arr = identityToken.split("\\.");
        String decode = new String(Base64.decodeBase64(arr[1]));
        String substring = decode.substring(0, decode.indexOf("}") + 1);
        return JSON.parseObject(substring);
    }

    /**
     * 获取苹果的公钥
     *
     * @return
     */
    public static JSONArray getAuthKeys(String type) {
        String url = "https://appleid.apple.com/auth/keys";
        RestTemplate restTemplate = new RestTemplate();
        JSONObject json = restTemplate.getForObject(url, JSONObject.class);
        if (json != null) {
            return json.getJSONArray("keys");
        }
        return null;
    }

    /**
     * 对前端传来的identityToken进行验证
     *
     * @param jwt     对应前端传来的 identityToken
     * @param authKey 苹果的公钥 authKey
     * @return
     * @throws Exception
     */
    public static Boolean verifyExc(String jwt, JSONObject authKey,String type) throws Exception {

        Jwk jwa = Jwk.fromValues(authKey);
        PublicKey publicKey = jwa.getPublicKey();

        String aud = "";
        String sub = "";
        if (jwt.split("\\.").length > 1) {
            String claim = new String(Base64.decodeBase64(jwt.split("\\.")[1]));
            aud = JSONObject.parseObject(claim).get("aud").toString();
            sub = JSONObject.parseObject(claim).get("sub").toString();
        }
        JwtParser jwtParser = Jwts.parser().setSigningKey(publicKey);
        jwtParser.requireIssuer("https://appleid.apple.com");
        jwtParser.requireAudience(aud);
        jwtParser.requireSubject(sub);

        try {
            Jws<Claims> claim = jwtParser.parseClaimsJws(jwt);
            if (claim != null && claim.getBody().containsKey("auth_time")) {
                System.out.println(claim);
                return true;
            }
            return false;
        } catch (ExpiredJwtException e) {
//            Log.error("apple identityToken expired", e);
            return false;
        } catch (Exception e) {
//            Log.error("apple identityToken illegal", e);
            return false;
        }
    }

//    public static void main(String[] args) throws Exception {
////        JSONObject jsonObject = JWTutil.parserIdentityToken("eyJraWQiOiJUOHRJSjF6U3JPIiwiYWxnIjoiUlMyNTYifQ.eyJpc3MiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoiY29tLnN0b3JlZC5wb3dlci5zcHRhcHAiLCJleHAiOjE3MjkzMDc2NzUsImlhdCI6MTcyOTIyMTI3NSwic3ViIjoiMDAxOTU0LmNlZThjMTgyYWQ4ODQ2MTk4YmRlNDM1MzcwOWQxMjZhLjA0MTkiLCJjX2hhc2giOiJqVm52WVRSal9qV0NGQnk0Y3VRZ2xBIiwiZW1haWwiOiIzMTQ4ODY3NDVAcXEuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1dGhfdGltZSI6MTcyOTIyMTI3NSwibm9uY2Vfc3VwcG9ydGVkIjp0cnVlfQ.BiAoEYej-LUs8N6WAF4r4sKeeNzAPmLJ93Dih3Z1RqRG14ORXZFhMKI6sgMvB6FYGRLAYYDm1PGyr7C1HrtapEjr9XqQXHPOBGaE-V8_oLj6a4BIVYphq0VcTTwGrqYk7HliR3HWY-5KRDP7l3XHcjDoNvsy0u0-Nf6LMmhOCedshFkoT9ebMbUthHGyTQN7RDMqhXY_6Al0hZPUlm0dpuM6PqJWRpZpm8gKwji3G4LlHJhRgiyp8JWbpGsvsh4EHipZDgLaGR0LZNvEOrIU4IsHRIaUR0aubW75BqIW23fCswfJuPkn0YpGHO0VcAzwQOpF_-EslEnAF5KBp1OtLw");
////        System.out.println(jsonObject);
//        JSONArray authKeys = JWTutil.getAuthKeys();
//        System.out.println(authKeys);
//        Boolean b = JWTutil.verifyExc("eyJraWQiOiJUOHRJSjF6U3JPIiwiYWxnIjoiUlMyNTYifQ.eyJpc3MiOiJodHRwczovL2FwcGxlaWQuYXBwbGUuY29tIiwiYXVkIjoiY29tLnN0b3JlZC5wb3dlci5zcHRhcHAiLCJleHAiOjE3MjkzMDc2NzUsImlhdCI6MTcyOTIyMTI3NSwic3ViIjoiMDAxOTU0LmNlZThjMTgyYWQ4ODQ2MTk4YmRlNDM1MzcwOWQxMjZhLjA0MTkiLCJjX2hhc2giOiJqVm52WVRSal9qV0NGQnk0Y3VRZ2xBIiwiZW1haWwiOiIzMTQ4ODY3NDVAcXEuY29tIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1dGhfdGltZSI6MTcyOTIyMTI3NSwibm9uY2Vfc3VwcG9ydGVkIjp0cnVlfQ.BiAoEYej-LUs8N6WAF4r4sKeeNzAPmLJ93Dih3Z1RqRG14ORXZFhMKI6sgMvB6FYGRLAYYDm1PGyr7C1HrtapEjr9XqQXHPOBGaE-V8_oLj6a4BIVYphq0VcTTwGrqYk7HliR3HWY-5KRDP7l3XHcjDoNvsy0u0-Nf6LMmhOCedshFkoT9ebMbUthHGyTQN7RDMqhXY_6Al0hZPUlm0dpuM6PqJWRpZpm8gKwji3G4LlHJhRgiyp8JWbpGsvsh4EHipZDgLaGR0LZNvEOrIU4IsHRIaUR0aubW75BqIW23fCswfJuPkn0YpGHO0VcAzwQOpF_-EslEnAF5KBp1OtLw", JWTutil.getAuthKeys().getJSONObject(0));
//        System.out.println(b);
//
//    }


}
